﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace RTUDataAcquisition.AppCode
{
    public class HeartCheckTimer
    {
        public class HeartCmd
        {
            public string key { get; set; }
            public int type { get; set; } = 1;
        }
        private Timer _timer;
        public static void Register(string HeartCheckTimerIP, int HeartCheckTimerPort, string key, int interVal = 5000)
        {
            if (!string.IsNullOrEmpty(HeartCheckTimerIP) && HeartCheckTimerPort != 0 && !string.IsNullOrEmpty(key))
            {
                if (interVal <= 5000)
                {
                    interVal = 5000;
                }
                Task.Run(() =>
                {
                    while (true)
                    {
                        try
                        {
                            // 创建TCP客户端
                            using (TcpClient client = new TcpClient(HeartCheckTimerIP, HeartCheckTimerPort))
                            {
                                client.ReceiveTimeout = 5000;
                                client.SendTimeout = 5000;
                                // 获取网络流
                                using (NetworkStream stream = client.GetStream())
                                {
                                    byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new HeartCmd { key = key, type = 1 }));
                                    // 发送数据到服务器
                                    stream.Write(data, 0, data.Length);
                                }
                            }
                        }
                        catch (Exception)
                        {


                        }
                        Thread.Sleep(interVal);
                    }
                });
            }
        }
    }
}
